package cn.junechiu.mytodo

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import io.realm.RealmResults
import org.jetbrains.anko.sdk25.coroutines.onClick

/**
 * Created by android on 2017/11/2.
 */
class TodoAdapter(context: Context,
                  realmResults: RealmResults<Todo>, click: ItemClickListener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var realmResults: RealmResults<Todo>? = null;

    private var context: Context? = null;

    private var click: ItemClickListener? = null;

    init {
        this.realmResults = realmResults
        this.context = context
        this.click = click
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
        val todo = realmResults!![position]
        (holder as ViewHolder).todoTitle.setText(todo!!.title)
        holder.todoContent.setText(todo!!.content)
        holder.itemView.onClick {
            click!!.onClick(holder.itemView, todo)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
        if (viewType === -1) {
            val v = View.inflate(context!!, R.layout.empty_view, null)
            return EmptyViewHolder(v)
        }
        val v = View.inflate(context!!, R.layout.todo_item, null)
        return ViewHolder(v)
    }

    override fun getItemCount(): Int {
        return realmResults!!.size
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {

        @BindView(R.id.todo_item_todo_title)
        lateinit var todoTitle: TextView

        @BindView(R.id.todo_item_todo_content)
        lateinit var todoContent: TextView

        init {
            ButterKnife.bind(this, view)
        }
    }

    inner class EmptyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    }

    interface ItemClickListener {
        fun onClick(caller: View, todo: Todo)
    }

}